package com.ys.utils.alipay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.*;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.ys.utils.alipay.config.AlipayConfig;
import com.ys.utils.alipay.config.YsAlipayConfig;
import com.ys.utils.alipay.enums.AlipayField;
import com.ys.utils.alipay.model.AliNotifyAppInfo;
import com.ys.utils.alipay.model.AliNotifyInfo;
import com.ys.utils.alipay.model.AlipayFields;
import com.ys.utils.alipay.model.MsgInfo;
import com.ys.utils.base.j2se.DateHandler;
import com.ys.utils.base.j2se.MapHandler;
import com.ys.utils.base.j2se.StringHandler;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author 但何非
 * @Date 2022/10/26 20:24
 * @ClassName: AlipayHander
 * @Description:
 * @Version:
 */
@Slf4j
public class AliPayHandler {
    private Map<String, AlipayConfig> alipayConfigMap = new HashMap<>();

    private Map<String, DefaultAlipayClient> defaultAlipayClient = new HashMap<>();

    private AlipayConfig alipayConfig = new AlipayConfig();


    public AliPayHandler(Map<String, String> propertiesProxy) {
        //所有支付宝账户
        if (StringHandler.isNotEmpty(propertiesProxy.get("ys.apipay.appid"))) {
//            String appId = propertiesProxy.get("free.activity.ali.pay.appid.list");
            List<String> obj = JSONObject.parseArray(propertiesProxy.get("ys.apipay.appid"),String.class);
            for (String appId : obj) {
                //加载支付宝商户列表
                try {
                    if(StringHandler.isEmpty(propertiesProxy.get("ys.alipay.app.cpk.crt."+appId))){
                        log.info(appId+".app.cpk.crt文件不存在");
                        continue;
                    }
                    CertAlipayRequest certAlipayRequest = new CertAlipayRequest ();
                    certAlipayRequest.setAppId(appId);
                    certAlipayRequest.setFormat("JSON");
                    certAlipayRequest.setCharset("UTF-8");
                    certAlipayRequest.setSignType("RSA2");
                    certAlipayRequest.setPrivateKey(propertiesProxy.get("ys.alipay.private.key."+appId));
                    certAlipayRequest.setCertPath(propertiesProxy.get("ys.alipay.app.cpk.crt."+appId));
                    certAlipayRequest.setRootCertPath(propertiesProxy.get("ys.alipay.app.rc.crt."+appId));
                    certAlipayRequest.setAlipayPublicCertPath(propertiesProxy.get("ys.alipay.app.ali.cpk.crt."+appId));
                    certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
                    defaultAlipayClient.put(appId, new DefaultAlipayClient(certAlipayRequest));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    public AliPayHandler(YsAlipayConfig ysAlipayConfig) {
        try {
            CertAlipayRequest certAlipayRequest = new CertAlipayRequest ();
            certAlipayRequest.setAppId(ysAlipayConfig.appId);
            certAlipayRequest.setFormat("JSON");
            certAlipayRequest.setCharset("UTF-8");
            certAlipayRequest.setSignType("RSA2");
            certAlipayRequest.setPrivateKey(ysAlipayConfig.privateKey);
            certAlipayRequest.setCertPath(ysAlipayConfig.appCpkCrt);
            certAlipayRequest.setRootCertPath(ysAlipayConfig.appRcCrt);
            certAlipayRequest.setAlipayPublicCertPath(ysAlipayConfig.aliCpkCrt);
            certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
            defaultAlipayClient.put(ysAlipayConfig.appId, new DefaultAlipayClient(certAlipayRequest));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public AliPayHandler(String test) {
        try {
            if("test".equals(test)) {
                CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
                certAlipayRequest.setFormat("JSON");
                certAlipayRequest.setCharset("UTF-8");
                certAlipayRequest.setSignType("RSA2");
                certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
                certAlipayRequest.setAppId("2021003187690103");
                certAlipayRequest.setPrivateKey("MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCVF+ZfYu1ALnL4T2RjhScIIXkgm0F8D63wF9zPB6WMJjwzjtv9ZG/A7eo1qLldX/Gx0ex/SEe2SsLSBXp2JvcDMjfkGrNqD7kgTjZlE6jBYvnr+QIq8obR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T9VMT3HPT1sw9XpnZAF66orN7LeicSaUZXUCgYBt3ynykrA3UrjDqGUvFV4E8QLiJJO0n9CRadJbXHccfQdPUMN1bLflNzpfWq/1m9wJ3D3yCcJqB7rKeoSSzgN81/Nl0qq6P8nT1nuvjQ3ElEZa/PRGNWa4oDxqDB2KUF5t2CQtNOzlpqO5xSmfXO+6Mwu5CifkliU1hnJHAhMgwQKBgArttBFttJOJ4zkyC7GZwgsUB4h8fumnl94h1vk1m1VgCS1N+qkeNXGfZKI243j+aIcLnviQuiBLjNj4pVeufu02MvPsw4Lj6nE3SIBqOvC4hmGfFdimAMRuuXyoAzf36U6ZpbKmcheLsyr8/8JrCUeLUbYLGGsOyZvcbBlh1K1k");
                certAlipayRequest.setCertPath("D:\\\\appCertPublicKey_2021003187690103.crt");
                certAlipayRequest.setRootCertPath("D:\\\\alipayRootCert.crt");
                certAlipayRequest.setAlipayPublicCertPath("D:\\\\alipayCertPublicKey_RSA2.crt");
                defaultAlipayClient.put("2021003187690103", new DefaultAlipayClient(certAlipayRequest));

//                certAlipayRequest.setAppId("2021003184688936");
//                certAlipayRequest.setPrivateKey("MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCZJUqTrv8e6Pbjr45KGAa5t+a8G0f8khR+P/hSO374TeU2pbGXMftd37bCQdQUaLuAn3qk26rU3rezF0fGStEPssASIhkuLMzwJ2vP2T/PNsJ/xqTictGDS14F09nApHkXIzea6MR24Pw2Wur3nMZaNiSHnkW3/bbtZ8Z0nJkRmeF4EPqYku0QhlfSKQRTdQt97p596kJav7Ry5fM/1Cohp1EAG16c0vXw+ShPUD5HE5uo8eJITrZC19EQIKNmSRA+v8aXR70QmsQZ3nSv7mUllT6yOineKQnW1G50dcs7N4bNOJkKRb8nsH7511FShNnkxOXtO6Ty9eP7MeeDiMNJAgMBAAECggEAY3oPqUKAwUk+JcOBP6u/op9MJ1/pMKyK1z8iQ/gVj6C5hPe4FagHyYBprGEqK1+ke/Ybq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VIGcOF6RG3MrB1nyc0u0kpJCFxMYVLDbK7GMby1VluAf2C8/DO1vhHGb61813w=");
//                certAlipayRequest.setCertPath("E:\\\\appCertPublicKey_2021003184688936.crt");
//                certAlipayRequest.setRootCertPath("E:\\\\alipayRootCert.crt");
//                certAlipayRequest.setAlipayPublicCertPath("E:\\\\alipayCertPublicKey_RSA2.crt");
//                defaultAlipayClient.put("2021003184688936", new DefaultAlipayClient(certAlipayRequest));

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public AliPayHandler(String test,int type) {
        try {
            if("test".equals(test)) {
                CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
                certAlipayRequest.setFormat("JSON");
                certAlipayRequest.setCharset("UTF-8");
                certAlipayRequest.setSignType("RSA2");
                certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
                certAlipayRequest.setAppId("2021003157650254");
                certAlipayRequest.setPrivateKey("MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCOJ7lT/M8BjQrxvph8mOnICLEpdFZENIpHu5z0rOVfga32WTz462dnSU7O4E5NkyXI9Eth9JT3maWILPaiOmxpgbRv1/M8FlRMwLp4Khw11fbiCdwe3H12IXa8O5wf33G69muvpYQYoujYc6HScPDHuEn0+LpuzzZzKvX8OJBrLcoH+W9x3e3H5MgLgJlhafkv5GmYXjUgnaIbON7fYoaeq9Ie6TFzyrhn6D0DNZbrKPKTKxL7HGnzM4D7z4wfcTpVZowlnBVVXJzJQ+iDGcaaZvJLUM5ktgMBztravzVgA2OMrugklTT3ewtveomNb3E8i4DVnqKGl7NxAqcLkGnbAgMBAAECggEAHfxDG3Q4NhuKM3QAtkeLCKbMt/HSQJDUmkz4zqOpvnucNlqcgeUl6qOL/BdUbQic78aYIBF3WsMOJ6tUWuP3+klhxjXHGOWc4pPEwZQgXzrC2Os7g0b/L+vfH9VzGUYIt2dDT8maE5hJhV7ew4UPRRGaiBHvQXB0C9cEDC/iRrkRDMwVp8f19edrI/LYeTYmW1lKyOoNn9w+Kd4B3IzVP1G+w5C1vjli5PW/SZgiT690L6/bukwmRdMUk1cDKfmQ1GPCeNM+Af7c3TRk44CdM2nIfvabj2gD3WllO5DVl5IRANsp+6FzB5TFfHng2Z1BwuAzcA2M26paDmqvRvBgAQKBgQDRyAbG/qsVG5cVkq1vN6HAjo7vXpHA/0Q/m5bdAxeQWaJklPec32sQNlIQ3pjAXKpXOw/cpMvTDONgbrCU3OuRspNmVHQRody5oKKCvCwMm5x3WcFPnSCCG0PIzxn8mCAG41feUm8jMNc4HXGkJvlashlewk4EaDn1ifaFX98diQKBgQCteXuAYN9VKDQyQu+s5yQUwCe79nMluXZ1WS9rcVqh5X/7Xc4mFK+i5BffHkDECpwqLMWq48xuRUA7GVnO8f11aiWv9E9Lmqsq72wGhQyHQQgvhbmrtI4JGKsFglkNXawXkgDpZhXMRn7XveX7jsrqGAoEJRMLk9y/OLzETql3QwKBgQDOJSLLz5ws/NTF5UI7BU8VGsHI5YSTRAU8AFgKzSwNtJdJAb4lUMMzxj10yFkQxr65Q5e9uc91kLernno1fraakQIZz6nTXdy6KOkpUWJz7UKfYfr9kilM0SAWJ7Wgq5jlS+if1x/RVABZ600uAwKMJnGZ1ZS27fjumWk//UsSCQKBgQCmLUV9iU7niIfXzf9CpnkN17U4fbF4Zd1wNGsUhZXImMyswwODvzUw2Ud02Mo6Ad/vFsyUE3v19ii9dF9vuqiOHYzUrTh4uEVX79qPtEx4FHf+7h8auO+HDzZlJKSiBSWhvp9Y9g3TjYRcrvDstbDz5utRZSKFaLOCCpvpgWEdeQKBgQCVea7SxcJ54v/u6zbrQlovlma2vlJBqGMS0Mkzaed9E1UPvXi1TDgOmdMBIp18ozop7KadWtfYZmBVv/d1ijHrL/qhmEySZ5TRULAX4Kbrk37NYDti55Z8jktVzwfyTZS/dpMpBN7MY+Si06yfiLO179v2FzS3xEuVHV6mKPHnpw==");
                certAlipayRequest.setCertPath("E:\\\\ys\\appCertPublicKey_2021003157650254.crt");
                certAlipayRequest.setRootCertPath("e:\\\\ys\\alipayRootCert.crt");
                certAlipayRequest.setAlipayPublicCertPath("e:\\\\ys\\alipayCertPublicKey_RSA2.crt");
                defaultAlipayClient.put("2021003157650254", new DefaultAlipayClient(certAlipayRequest));

//                certAlipayRequest.setAppId("2021003184688936");
//                certAlipayRequest.setPrivateKey("MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCZJUqTrv8e6Pbjr45KGAa5t+a8G0f8khR+P/hSO374TeU2pbGXMftd37bCQdQUaLuAn3qk26rU3rezF0fGStEPssASIhkuLMzwJ2vP2T/PNsJ/xqTictGDS14F09nApHkXIzea6MR24Pw2Wur3nMZaNiSHnkW3/bbtZ8Z0nJkRmeF4EPqYku0QhlfSKQRTdQt97p596kJav7Ry5fM/1Cohp1EAG16c0vXw+ShPUD5HE5uo8eJITrZC19EQIKNmSRA+v8aXR70QmsQZ3nSv7mUllT6yOineKQnW1G50dcs7N4bNOJkKRb8nsH7511FShNnkxOXtO6Ty9eP7MeeDiMNJAgMBAAECggEAY3oPqUKAwUk+JcOBP6u/op9MJ1/pMKyK1z8iQ/gVj6C5hPe4FagHyYBprGEqK1+ke/Ybqj5uBvvsg05Z9vneNr47eQvhI1dCf7R7mXVat3SwfmM/8z/1y70HA+4KgdHUPi1IDz2ncDjQW1ZPTivtw+drbxRl4Q/S5P8Fr/WQkBdFBepYdaTO0eHpgDsc3Ffsknj0r5L0IsH5GvqUZZyuqxDSGVrf5TPcAyMINUJff/t5IZcVzJ8i+Y/WLm1ic/T5DS5TfWJdY9su3JT39q0OqJRy1VrCGduuV+UAiuexQ/OdUyx6o28eJ9zMtabngflz3J54VuOdAFxciQkNbg2LyQKBgQD/PTuXM7dxBrLT58lyQCrr6wCE13UWdBKOl8uZsBfx5IJQLXz6h/lu1eOCl8JY/4n3DeAKnDrVkkql5p/UxcDAv7X26Er0yt+J+gsuTnEf7LBKl/TGU9VFAbNnje2TABXyD2J8WNA2iLH6hCby4RFyEYWNMjGLyiPjbpbLNPUyRwKBgQCZmic+U3hpzQk+plTcGzkKBMt9p1NpqalWCAO6+BCsYB9znywczrhlvHjQ4YzI2EqynHCDOwo45K9HiGaYLwXSIqL/kNYDipV7MXI8XT/mO7O6wgR+OaAtQXNKbAuRdpnC+0jmujp7ez5Un+grGwd8bWw5/invYH+P3pwzxwkV7wKBgQC8WYlh+M4D4DeS3Fbxspx5379QSFalLR6Mj0O1tBbXcBMh649wqWrN+ZScSDUoy9oZr+mGqudXt07Swi9sKkolctNq0tyNbDAtd5FMqKIeNuGZCi2dNTwKYkjrv/ZzJfsL14KL1FZCB/mermq3jJL9JCTznvik+ZQmPvOUHQ5b/QKBgFNQLLb+mVJxtvD3URHt5htMDH/EMVcfgky6niNch9ancIfLLycU7Smpd7J8lFsgDiwg9FoJvPqs93GKR3OGFdcrmFOcYKidE4U1hau+PHmJqmvC7qL0aLADTyBvyDqHJNGAcMNNAYmWiHFoJoqy53WS+F/gPyiqo6YKbZkb/Q6bAoGAYbJEInsnPno981/DTTGrT19XNsXDVD89Wl38XtYL4LI+oGNt5c79WckydKyWd1gGfeoo9/KsccCZKL4QMhYHwC3BEOs29rB8VoX0BGTT8rF98VIGcOF6RG3MrB1nyc0u0kpJCFxMYVLDbK7GMby1VluAf2C8/DO1vhHGb61813w=");
//                certAlipayRequest.setCertPath("E:\\\\appCertPublicKey_2021003184688936.crt");
//                certAlipayRequest.setRootCertPath("E:\\\\alipayRootCert.crt");
//                certAlipayRequest.setAlipayPublicCertPath("E:\\\\alipayCertPublicKey_RSA2.crt");
//                defaultAlipayClient.put("2021003184688936", new DefaultAlipayClient(certAlipayRequest));

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
//    public AliPayHandler(PropertiesProxy propertiesProxy,String name) {
//        if (StringHandler.isNotEmpty(propertiesProxy.get("payment.alipay.appId"))) {
////            String appId = propertiesProxy.get("payment.alipay.appId");
//            List<String> obj = ListHandler.str2str(propertiesProxy.get("free.activity.ali.pay.appid.list"));
//            for (String appId : obj) {
//                if(StringHandler.isEmpty(AliPayHandler.class.getResource("/"+appId+".app.cpk.crt"))){
//                    logs.info(appId+".app.cpk.crt文件不存在");
//                    continue;
//                }
//                AlipayConfig alipayConfig = new AlipayConfig();
//                alipayConfig.APPID = appId;
//                alipayConfig.RSA_PRIVATE_KEY = propertiesProxy.get("payment.alipay.private.key." + appId, "");
//                alipayConfig.notify_url = propertiesProxy.get("aliPayNotifyUrl_"+ Logs.myPro);
//                if(!Logs.isOnline()){
//                    alipayConfig.notify_url = propertiesProxy.get("aliPayNotifyUrl_"+Logs.myPro+"_"+Logs.getEnvironmentName());
//                }
//                alipayConfig.return_url = propertiesProxy.get("aliPayReturnUrl_"+ Logs.myPro);
//                if(!Logs.isOnline()){
//                    alipayConfig.return_url = propertiesProxy.get("aliPayReturnUrl_"+Logs.myPro+"_"+Logs.getEnvironmentName());
//                }
//                alipayConfig.ALIPAY_PUBLIC_KEY = propertiesProxy.get("payment.alipay.public.key." + appId, "");
//                alipayConfig.log_path = "";
//                alipayConfigMap.put(appId, alipayConfig);
//            }
//        }
//    }
    /**
     * @ 名称:支付宝支付参数
     * @ 创建人: dhf
     * @ 参数： out_trade_no 订单编号
     * @ 参数： total_amount 金额（元）
     * @ 参数： subject      标题
     * @ 参数： body         备注
     * @ 参数： type         类型 webPay（网站支付） payNative（扫码支付）
     * @ 创建时间: 2021/12/3
     * @ 修改人和其它信息
     * @ 返回值: com.alibaba.fastjson.JSONObject
     */
    public JSONObject bizContent(String out_trade_no, String total_amount, String subject, String body, String type,String time_expire) {
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", out_trade_no);
        bizContent.put("total_amount", total_amount);
        bizContent.put("subject", subject);
        if(StringHandler.isNotEmpty(time_expire)){
            bizContent.put("time_expire", time_expire);
        }
        //网站
        if (type.equals("webPay"))
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        //扫码
        if (type.equals("payNative")) {
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
            bizContent.put("body", body);
        }
        //手机网站支付
        if (type.equals("H5")) {
            bizContent.put("product_code", "QUICK_WAP_WAY");
        }
        //app支付
        if (type.equals("app")) {
            bizContent.put("product_code", "QUICK_MSECURITY_PAY");
        }
        return bizContent;
    }

    /**
     * @ 名称:支付宝退款参数
     * @ 创建人: dhf
     * @ 参数： out_trade_no 退款订单号
     * @ 参数： refund_amount 退款金额
     * @ 参数： refund_reason 退款原因说明
     * @ 参数： trade_no       支付宝交易号
     * @ 参数： out_trade_no   退款请求号
     * @ 创建时间: 2021/12/3
     * @ 修改人和其它信息
     * @ 返回值: com.alibaba.fastjson.JSONObject
     */
    public JSONObject bizContent(String out_trade_no, String refund_amount, String refund_reason,String trade_no) {
        JSONObject bizContent = new JSONObject();
//        bizContent.put("out_trade_no", out_trade_no);
        bizContent.put("refund_amount", refund_amount);
        bizContent.put("trade_no", trade_no);
        bizContent.put("refund_reason", refund_reason);
        bizContent.put("out_request_no", out_trade_no);
        return bizContent;
    }

    /**
     * @ 名称:支付宝网页支付
     * @ 创建人: dhf
     * @ 参数： appId 支付宝账号
     * @ 参数： bizContent 参数
     * @ 创建时间: 2021/12/3
     * @ 修改人和其它信息
     * @ 返回值:String
     */
    public MsgInfo webPay(String appId, JSONObject bizContent) throws AlipayApiException {
        DefaultAlipayClient alipayClient = this.defaultAlipayClient.get(appId);
        MsgInfo msgInfo = new MsgInfo();
        if(StringHandler.isEmpty(alipayClient)) {
            msgInfo.isSuccess = false;
            msgInfo.errMsg="";
        }
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(alipayConfig.notify_url);
        request.setReturnUrl(alipayConfig.return_url);
        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        msgInfo.isSuccess = true;
        msgInfo.msg=response.getBody();
        return msgInfo;
    }

    /**
     * @ 名称:支付宝扫码支付
     * @ 创建人: dhf
     * @ 参数： appId 支付宝账号
     * @ 参数： bizContent 参数
     * @ 创建时间: 2021/12/3
     * @ 修改人和其它信息
     * @ 返回值:String
     */
    public MsgInfo payNative(String appId, JSONObject bizContent) throws AlipayApiException {
        DefaultAlipayClient alipayClient = this.defaultAlipayClient.get(appId);
        MsgInfo msgInfo = new MsgInfo();
        if(StringHandler.isEmpty(alipayClient)) {
            msgInfo.isSuccess = false;
            msgInfo.errMsg="";
            return msgInfo;
        }
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setNotifyUrl(alipayConfig.notify_url);
        request.setBizContent(bizContent.toString());
        AlipayTradePrecreateResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            msgInfo.isSuccess = true;
            msgInfo.msg=response.getQrCode();
        } else {
            msgInfo.isSuccess = false;
            msgInfo.errMsg=response.getSubCode()+":"+response.getMsg();
        }
        return msgInfo;
    }
    /**
     * @ 名称:支付宝h5支付
     * @ 创建人: dhf
     * @ 参数： appId 支付宝账号
     * @ 参数： bizContent 参数
     * @ 创建时间: 2021/12/3
     * @ 修改人和其它信息
     * @ 返回值:String
     */
    public MsgInfo h5Pay(String appId, JSONObject bizContent) throws AlipayApiException {
        DefaultAlipayClient alipayClient = this.defaultAlipayClient.get(appId);
        MsgInfo msgInfo = new MsgInfo();
        if(StringHandler.isEmpty(alipayClient)) {
            msgInfo.isSuccess = false;
            msgInfo.errMsg="";
            return msgInfo;
        }
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest ();
        request.setNotifyUrl(alipayConfig.notify_url);
        request.setBizContent(bizContent.toString());
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request);
        if (response.isSuccess()) {
            msgInfo.isSuccess = true;
            msgInfo.msg=response.getBody();
        } else {
            msgInfo.isSuccess = false;
            msgInfo.errMsg=response.getSubCode()+":"+response.getMsg();
        }
        return msgInfo;
    }
    /**
     * @ 名称:app支付
     * @ 创建人: dhf
     * @ 参数： null
     * @ 创建时间: 2021/12/14
     * @ 修改人和其它信息
     * @ 返回值:
     */
    public MsgInfo appPay(String appId, JSONObject bizContent,String notifyUrl) throws AlipayApiException {
        DefaultAlipayClient alipayClient = this.defaultAlipayClient.get(appId);
        MsgInfo msgInfo = new MsgInfo();
        if(StringHandler.isEmpty(alipayClient)) {
            msgInfo.isSuccess = false;
            msgInfo.errMsg="";
            return msgInfo;
        }
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest ();
        request.setNotifyUrl(notifyUrl);
        request.setBizContent(bizContent.toString());
        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
        if (response.isSuccess()) {
            msgInfo.isSuccess = true;
            msgInfo.msg=response.getBody();
        } else {
            msgInfo.isSuccess = false;
            msgInfo.errMsg=response.getSubCode()+":"+response.getMsg();
        }
        return msgInfo;
    }
    /**
     * @ 名称:支付宝退款
     * @ 创建人: dhf
     * @ 参数： appId 支付宝账号
     * @ 参数： bizContent 参数
     * @ 创建时间: 2021/12/3
     * @ 修改人和其它信息
     * @ 返回值: autumn.tools.ali.model.MsgInfo
     */
    public MsgInfo refund(String appId,  JSONObject bizContent) throws AlipayApiException {
        DefaultAlipayClient alipayClient = this.defaultAlipayClient.get(appId);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizContent(bizContent.toJSONString());
        AlipayTradeRefundResponse response = alipayClient.certificateExecute(request);
        MsgInfo msgInfo = new MsgInfo();
        if(response.isSuccess()){
            msgInfo.isSuccess = response.isSuccess();
            msgInfo.code = response.getCode();
            msgInfo.thirdOrder= response.getTradeNo();
            msgInfo.orderSn=response.getOutTradeNo();
            msgInfo.paymentTime= DateHandler.getLongFormatDate();
        } else{
            msgInfo.isSuccess = false;
            msgInfo.code = response.getCode();
            msgInfo.errMsg=response.getCode()+":"+response.getMsg();
        }
        return msgInfo;
    }

    /**
     * @author 但何非
     * @dateTime 2022/10/26 21:50
     * @params
     * @param appId:
     * @param bizModel:
     * @return
     * @return com.ys.utils.alipay.model.MsgInfo
     * @Description:支付宝转账
     */
    public MsgInfo trans(String appId,  AlipayObject bizModel) throws AlipayApiException {
        AlipayClient alipayClient = this.defaultAlipayClient.get(appId);
        AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
        request.setBizModel(bizModel);
        AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
        MsgInfo msgInfo = new MsgInfo();
        if(response.isSuccess() || response.getSubCode().equals("SYSTEM_ERROR")){
            msgInfo.isSuccess = response.isSuccess();
            msgInfo.code = response.getCode();
            msgInfo.thirdOrder= response.getOrderId();
            msgInfo.orderSn=response.getOutBizNo();
            msgInfo.payFundOrderId = response.getPayFundOrderId();
            msgInfo.paymentTime= DateHandler.getLongFormatDate();
        } else{
            msgInfo.isSuccess = false;
            msgInfo.code = response.getCode();
            msgInfo.msg=response.getCode()+":"+response.getMsg();
            msgInfo.errMsg=response.getCode()+":"+response.getSubMsg();
        }
        return msgInfo;
    }
    /**
     * @ 名称:支付回调验证，及处理信息
     * @ 创建人: dhf
     * @ 参数： notifyInfo
     * @ 创建时间: 2021/12/3
     * @ 修改人和其它信息
     * @ 返回值: autumn.tools.ali.model.MsgInfo
     */
    public MsgInfo notify(AliNotifyInfo notifyInfo,String alipayPublicCertPath) throws  AlipayApiException {
        //获取支付宝POST过来反馈信息
        Map<String, String> webMap =  MapHandler.obj2StrNotNull(MapHandler.obj2map(notifyInfo));
        Map<String, String> notifyParams = new HashMap<String, String>();
        // 这里还是建议直接从request中获取map参数，兼容支付宝修改或增减参数
        for (AlipayField f : AlipayFields.WEB_PAY_NOTIFY){
            notifyParams.put(f.field(), webMap.get(f.field()));
        }
        boolean signVerified = AlipaySignature.rsaCertCheckV1(MapHandler.obj2StrNotNull(MapHandler.obj2map(notifyInfo)),
                alipayPublicCertPath,
                notifyInfo.charset, notifyInfo.sign_type); //调用SDK验证签名
        MsgInfo msgInfo = new MsgInfo();
        if(signVerified) {//验证成功
            if(notifyInfo.trade_status.equals("TRADE_SUCCESS")){
                msgInfo.isSuccess = signVerified;
                msgInfo.errMsg="支付成功";
                msgInfo.msg="success";
            }else{
                msgInfo.isSuccess = false;
                msgInfo.errMsg="支付失败";
                msgInfo.msg="fail";
            }
            msgInfo.thirdOrder= notifyInfo.trade_no;
            msgInfo.orderSn= notifyInfo.out_trade_no;
            msgInfo.paymentTime= StringHandler.isEmpty(notifyInfo.gmt_payment)?DateHandler.getLongFormatDate():DateHandler.getLongFormatDate(notifyInfo.gmt_payment);
        }else {//验证失败
            msgInfo.isSuccess = signVerified;
            msgInfo.msg="fail";
        }
        return msgInfo;
    }
    public MsgInfo appNotify(AliNotifyAppInfo notifyInfo, String alipayPublicCertPath) throws  AlipayApiException {
        Map<String, String> webMap =  MapHandler.obj2StrNotNull(MapHandler.obj2map(notifyInfo));
        boolean signVerified = AlipaySignature.rsaCertCheckV1(webMap,
                alipayPublicCertPath,
                notifyInfo.charset, notifyInfo.sign_type); //调用SDK验证签名
        MsgInfo msgInfo = new MsgInfo();
        if(signVerified) {//验证成功
            if(notifyInfo.trade_status.equals("TRADE_SUCCESS")){
                msgInfo.isSuccess = signVerified;
                msgInfo.errMsg="支付成功";
                msgInfo.msg="success";
            }else{
                msgInfo.isSuccess = false;
                msgInfo.errMsg="支付失败";
                msgInfo.msg="fail";
            }
            msgInfo.thirdOrder= notifyInfo.trade_no;
            msgInfo.orderSn= notifyInfo.out_trade_no;
            msgInfo.paymentTime= StringHandler.isEmpty(notifyInfo.gmt_payment)?DateHandler.getLongFormatDate():DateHandler.getLongFormatDate(notifyInfo.gmt_payment);
        }else {//验证失败
            msgInfo.isSuccess = signVerified;
            msgInfo.msg="fail";
        }
        return msgInfo;
    }
    /**
     * @ 名称:当前时间加分钟
     * @ 创建人: dhf
     * @ 参数： number
     * @ 创建时间: 2021/12/10
     * @ 修改人和其它信息
     * @ 返回值: java.lang.String
     */
    public static String getMinute(int number) {
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE, number);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(nowTime.getTime());
    }

    /**
     * @ 名称:支付订单查询
     * @ 创建人: dhf
     * @ 参数： appId
     * @ 参数： out_trade_no
     * @ 创建时间: 2021/12/14
     * @ 修改人和其它信息
     * @ 返回值:
     */
    public MsgInfo payOrder(String appId,String out_trade_no) throws AlipayApiException {
        DefaultAlipayClient alipayClient = this.defaultAlipayClient.get(appId);
        MsgInfo msgInfo = new MsgInfo();
        if(StringHandler.isEmpty(alipayClient)) {
            msgInfo.isSuccess = false;
            msgInfo.errMsg="";
            return msgInfo;
        }
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest ();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", out_trade_no);
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = alipayClient.certificateExecute(request);
        if (response.isSuccess()) {
            msgInfo.isSuccess = response.isSuccess();
            msgInfo.code = response.getCode();
            msgInfo.thirdOrder= response.getTradeNo();
            msgInfo.orderSn=response.getOutTradeNo();
            msgInfo.paymentTime= DateHandler.getLongFormatDate();
        } else {
            msgInfo.isSuccess = true;
            msgInfo.errMsg=response.getSubCode()+":"+response.getMsg();
        }
        return msgInfo;
    }

    /**
     * @ 名称:退款订单查询
     * @ 创建人: dhf
     * @ 参数： appId
     * @ 参数： out_trade_no
     * @ 创建时间: 2021/12/14
     * @ 修改人和其它信息
     * @ 返回值:
     */
    public MsgInfo refundOrder(String appId,String out_trade_no) throws AlipayApiException {
        DefaultAlipayClient alipayClient = this.defaultAlipayClient.get(appId);
        MsgInfo msgInfo = new MsgInfo();
        if(StringHandler.isEmpty(alipayClient)) {
            msgInfo.isSuccess = false;
            msgInfo.errMsg="";
            return msgInfo;
        }
        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", out_trade_no);
        request.setBizContent(bizContent.toString());
        AlipayTradeFastpayRefundQueryResponse response = alipayClient.certificateExecute(request);
        if (response.isSuccess()) {
            msgInfo.isSuccess = response.isSuccess();
            msgInfo.code = response.getCode();
            msgInfo.thirdOrder= response.getTradeNo();
            msgInfo.orderSn=response.getOutTradeNo();
            msgInfo.paymentTime= DateHandler.getLongFormatDate();
        } else {
            msgInfo.isSuccess = true;
            msgInfo.errMsg=response.getSubCode()+":"+response.getMsg();
        }
        return msgInfo;
    }

    public String sign(Map<String, String> keyValues,String secret) throws AlipayApiException {
        return AlipaySignature.getSignContent(keyValues)+"&sign="+AlipaySignature.sign(keyValues,secret,"UTF8","RSA2");
    }

    public DefaultAlipayClient getDefaultAlipayClient(String appid){
        if(StringHandler.isEmpty(defaultAlipayClient))
            return null;
        return defaultAlipayClient.get(appid);
    }
}
